package cn.ssq.controller;


import cn.ssq.domain.*;
import cn.ssq.service.*;
import cn.ssq.util.DateUtils;
import cn.ssq.util.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
public class IMController {
    @Autowired
    private SampleInfoService sampleInfoService;
    @Autowired
    private SampleToxinInfoService sampleToxinInfoService;
    @Autowired
    private CropCpeciesService cropCpeciesService;
    @Autowired
    private BacterialStrainfoService bacterialStrainfoService;
    @Autowired
    private SampleToxinService sampleToxinService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CropCategoryService cropCategoryService;
    //查询毒素信息
    @RequestMapping("/findSampleToxinInfo")
    @ResponseBody
    public String findSampleToxinInfo(Model model) {
        List<SampleToxinInfo> sampleToxinInfoList = sampleToxinInfoService.findSampleToxinInfo();
        model.addAttribute("sampleToxinInfoList", sampleToxinInfoList);
        return JSON.toJSONString(sampleToxinInfoList);
    }

    //查询农作物种类
    @RequestMapping("/findCropCpeciesLIst")
    @ResponseBody
    public String findCropCpecies(Model model) {
        List<CropCpecies> cropCpeciesLIst = cropCpeciesService.findCropCpeciesLIst();
        model.addAttribute("cropCpeciesLIst", cropCpeciesLIst);
        return JSON.toJSONString(cropCpeciesLIst);
    }

    //通过id回显样品信息
    @RequestMapping("/findById")
    //@ResponseBody
    public String findById(@RequestParam Integer sampleId , Model model){
        SampleInfo sampleInfo= sampleInfoService.findById(sampleId);;
        List<SampleToxinInfo> sampleToxinInfo = sampleToxinInfoService.findSampleToxinInfo();
        model.addAttribute("sampleInfo",sampleInfo);
        List<SampleToxin> sampleToxin = sampleInfo.getSampleToxin();
        model.addAttribute("sampleToxin",sampleToxin);
        model.addAttribute("sampleToxinInfo",sampleToxinInfo);

        return "editIM2";
    }
    //模糊查询
    @RequestMapping("/cxsys")
    @ResponseBody
    public Map<String,Object> selectLikeSampleId(@RequestParam Map<String, Object> map,@RequestParam Map map1 ,@RequestParam(required=true,defaultValue="1")Integer pageNum ) {
        PageInfo pageInfo = sampleInfoService.selectLikeSampleId(map, pageNum);
        map1.put("pageInfo",pageInfo);
        return map1;
    }


    //修改样品信息
    @RequestMapping("/updateSampleInfo")
    @ResponseBody
    public Result updateSampleInfo(@RequestParam Map<String, Object> map , @RequestParam(value = "word_addr", required = false) MultipartFile[] word_addr, @RequestParam(value = "txt_addr", required = false) MultipartFile[] txt_addr, @RequestParam(value = "picture_addr", required = false) MultipartFile[] picture_addr
            , Integer[] toxinId, String[] toxinCount, String[] original_num, String[] wordvalues, String[]txtvalues, String[] imgvalues) {
        System.out.println(map);
        String samid = (String) map.get("samid");
        int sampleId = Integer.parseInt(samid);
        int i3=0;
        int i4=0;
        Result result = new Result();
        int i5 = sampleInfoService.updateSampleInfo(map);
        //删除毒素
        sampleToxinService.updateToxin(sampleId);
        bacterialStrainfoService.updateBacterialStrainfo(sampleId);

        i4= sampleToxinService.insertTxon(sampleId, toxinId, toxinCount);
        List<String> originalnum = Arrays.asList(original_num);

        String wordsuffer = "";
        String txtsuffer = "";
        String picsuffer = "";

        String wordvalue = "";
        String txtvalue = "";
        String imgvalue = "";

        //分别用来存放三个集合上传完成之后的路径
        List<String> wordStrings = new ArrayList<String>();
        List<String> txtStrings = new ArrayList<String>();
        List<String> picStrings = new ArrayList<String>();

        //循环获取三个上传集合的后缀名称
        for (int i=0;i<word_addr.length;i++){
            //获取上传文件的名称
            String wordStrig = word_addr[i].getOriginalFilename();
            String txtStrig = txt_addr[i].getOriginalFilename();
            String picStrig = picture_addr[i].getOriginalFilename();
            //判断上传的文件名是不是空的
            if (wordStrig.length()>0){
                wordsuffer =  word_addr[i].getOriginalFilename().substring(wordStrig.lastIndexOf("."));
                //如果是空的就让他直接存储字符串
            }else {
                for (int j = 0; j < wordvalues.length; j++) {
                    wordStrings.add(wordvalues[j]);
                }
            }
            if (txtStrig.length()>0){
                txtsuffer =  txt_addr[i].getOriginalFilename().substring(txtStrig.lastIndexOf("."));
            }else {
                for (int j = 0; j < txtvalues.length; j++) {
                    txtStrings.add(txtvalues[i]);
                }
            }
            if (picsuffer.length()>0){
                picsuffer =  picture_addr[i].getOriginalFilename().substring(picStrig.lastIndexOf("."));
            }else {
                for (int j = 0; j < imgvalues.length; j++) {
                    picStrings.add(imgvalues[i]);
                }
            }
            //创建一个上传的文件路径
            String path = "D:/myfile/";
            long l = System.currentTimeMillis();
            String s = String.valueOf(l);
            //拼接上传的全路径
            String finalWordPath = path+s+wordsuffer;
            String finalTxtPath = path+s+txtsuffer;
            String finalPicPath = path+s+picsuffer;

            wordStrings.add(finalWordPath);
            txtStrings.add(finalTxtPath);
            picStrings.add(finalPicPath);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
        }
        for (int j=0;j<word_addr.length;j++){
            try {
                //进行上传操作
                word_addr[j].transferTo(new File(wordStrings.get(j)));
                txt_addr[j].transferTo(new File(txtStrings.get(j)));
                picture_addr[j].transferTo(new File(picStrings.get(j)));
                //循环把上传完成之后的路径存到list集合里面
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println(e);
            }
        }
            i3 = bacterialStrainfoService.addBacterialStrainfo(sampleId, originalnum,wordStrings , txtStrings, picStrings);
        if (i5+i3+i4>0){
            result.setFlag(true);
        }else {
            result.setFlag(false);
        }
        return result;

    }

    /**
     * 删除一个
     * @param ids
     * @return
     */
    @RequestMapping("/deleteSampleById")
    public String deleteSampleById( Integer[] ids){
        System.out.println(ids);
        Result result = sampleInfoService.delectSampleById(ids);
        return "IM";
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping("/deleteSampleByIds")
    @ResponseBody
    public Result deleteSampleByIds(Integer[] ids){
        //System.out.println(ids);
        Result result = sampleInfoService.delectSampleById(ids);
        return result;
    }

    /**
     *
     * 下载模板
     *
     */
    @RequestMapping("/download")
    @ResponseBody
    public  void  downloadSampleInfo(HttpServletResponse response, HttpServletRequest request) throws IOException {
        OutputStream os = null;// 输出流
        InputStream fis = new FileInputStream(request.getServletContext().getRealPath("/") + "file/样品信息.xlsx");// 手动创建一个elsx文件
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        String fileName = "样品信息.xlsx";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

    /**
     * 上传word文档
     * @param wordAddr
     */
    @RequestMapping("/upload")
    public void fileUpload(@RequestParam("wordAddr") MultipartFile[] wordAddr,@RequestParam("txtAddr") MultipartFile[] txtAddr,@RequestParam("pictureAddr") MultipartFile[] pictureAddr) {
        try {
            int len = wordAddr.length;
            for (int i = 0; i < len; i++) {
                MultipartFile file = wordAddr[i];
                if (file.isEmpty()) {
                    return;
                } else {
                    file.transferTo(new File( file.getName()));
                }
            }
            int lent = txtAddr.length;
            for (int i = 0; i < len; i++) {
                MultipartFile file = txtAddr[i];
                if (file.isEmpty()) {
                    return;
                } else {
                    file.transferTo(new File( file.getName()));
                }
            }
            int lenp = pictureAddr.length;
            for (int i = 0; i < len; i++) {
                MultipartFile file = pictureAddr[i];
                if (file.isEmpty()) {
                    return;
                } else {
                    file.transferTo(new File( file.getName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    /**
     * 样品导出
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/export")
    public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String message = "";

        //获取数据
        List<SampleInfo> list = sampleInfoService.findSampleInfoList();

        //excel标题
        String[] title = {"id","样品编号","农产品加工类别","是否取样","品种","省","市","县","乡","村","户","收获时间",
                "取样时间","取样人","采集时季节及气候特征","采集地,环境描述及信息描述",
                "真菌污染率","毒菌种类","菌株原始编号","文档信息","txt文件","图片信息"};

        //excel文件名
        String fileName = "sampleInfo"+System.currentTimeMillis()+".xls";

        //sheet名
        String sheetName = "样品信息表";

        String [][] content = new String[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            SampleInfo stu = list.get(i);
            String toxins = "";//毒素的字符串
            String cropCategory = "";//类别的字符串
            String cropCpe = "";//品种
            Integer id = stu.getId();
            content[i][0] = id+"";
            content[i][1] = stu.getSampleId()+"";
            Integer cropCategoryId = stu.getCropCategoryId();
            if (cropCategoryId==1){
                cropCategory+="水果类";
            }else if (cropCategoryId==2){
                cropCategory+="谷物类";
            }else if (cropCategoryId==3){
                cropCategory+="油料类";
            }else if (cropCategoryId==4){
                cropCategory+="坚果类";
            }else if (cropCategoryId==5){
                cropCategory+="香辛类";
            }else if (cropCategoryId==6){
                cropCategory+="饲料类";
            }
            content[i][2] = cropCategory+"";
            content[i][3] = stu.getFlag()+"";
            List<CropCpecies> cropCpecies = stu.getCropCpecies();
            for (int j=0;j<cropCpecies.size();j++){
                cropCpe+=cropCpecies.get(j).getCropSpecies();
            }
            content[i][4] = cropCpe+"";
            //省
            content[i][5] = stu.getProvince()+"";
            //市
            content[i][6] = stu.getCity()+"";
            //县
            content[i][7] = stu.getCounty()+"";
            //乡
            content[i][8] = stu.getTownship()+"";
            //村
            content[i][9] = stu.getVillage()+"";
            //户
            content[i][10] = stu.getHousehold()+"";
            String harvestTime="";//收货时间
            Date stuHarvestTime = stu.getHarvestTime();
            harvestTime = DateUtils.date2String(stuHarvestTime,"yyyy-MM-dd HH:mm:ss");
            content[i][11]=harvestTime+"";

            String samplingTime ="";
            Date stuSamplingTime = stu.getSamplingTime();
            samplingTime= DateUtils.date2String(stuSamplingTime, "yyyy-MM-dd HH:mm:ss");
            content[i][12] = samplingTime+"";
            content[i][13] = stu.getSamplingPeople()+"";
            content[i][14] = stu.getSeasonal()+"";
            content[i][15] = stu.getDescription()+"";
            content[i][16] = stu.getPollutionRate()+"";
            List<SampleToxinInfo> sampleToxinInfo = stu.getSampleToxinInfo();
            if (sampleToxinInfo.size()!=0){
                for (int j=0;j<sampleToxinInfo.size();j++){
                    toxins+=sampleToxinInfo.get(j).getToxinType()+",";
                }
                String substring = toxins.substring(0, toxins.length() - 1);
                content[i][17] = substring+"";
            }else {
                content[i][17] = null+"";
            }
            String bacters = "";
            String word = "";
            String txt = "";
            String png = "";

            List<BacterialStrainInfo> bacterialStrainInfos = stu.getBacterialStrainInfos();
            for (int j=0;j<bacterialStrainInfos.size();j++){
                bacters+=bacterialStrainInfos.get(j).getOriginalNum()+",";
                word+=bacterialStrainInfos.get(j).getWordAddr()+"-";
                txt+=bacterialStrainInfos.get(j).getTxtAddr()+"-";
                png+=bacterialStrainInfos.get(j).getPictureAddr()+"-";
            }
            String substr = bacters.substring(0, bacters.length()-1);
            String word1 = word.substring(0, word.length()-1);
            String txt1 = txt.substring(0, txt.length() - 1);
            String png1 = png.substring(0, png.length() - 1);
            content[i][18] = substr+"";
            content[i][19] = word1+"";
            content[i][20] = txt1+"";
            content[i][21] = png1+"";
            }



        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
            message = "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            message = "ERROR";
        }

        return null;
    }

    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 样品信息导入
     */

      @RequestMapping("/updateExcel")
 public String importExcelForSample(@RequestParam("file")MultipartFile file) throws Exception {
        List<List<Object>> list = ExcelUtil.getExcelList(file.getInputStream(), file.getOriginalFilename());
        for (int i = 0; i < list.size(); i++) {
            List<Object> li = list.get(i);
            //设置样品id
            String sampleId = li.get(1).toString();
            //设置产品加工类
            String cropCategory = (String) li.get(2);

            Integer categoryId = cropCategoryService.findCropCategory(cropCategory);
            String cropSpecies = (String) li.get(4);
            int cropCpeciesId = cropCpeciesService.findByCropCpecies(cropSpecies);
            String sheng = (String) li.get(5);
            String shi = (String) li.get(6);
            String xian = (String) li.get(7);
            String xiang = (String) li.get(8);
            String cun = (String) li.get(9);
            String hu = (String) li.get(10);
            String hTime = (String) li.get(11);
            String sTime = (String) li.get(12);
            String samPeople= (String) li.get(13);
            String seasonal = (String) li.get(14);
            String description = (String) li.get(15);
            String pollutionRate = (String) li.get(16);
            Integer isdel =0;



            String tooxin = (String) li.get(17);
            List<Integer> toxinId =new ArrayList<Integer>();
            String[] tooxins = tooxin.split(",");
            for (int i1 = 0; i1 < tooxins.length; i1++) {
                Integer toxinBynName = sampleToxinInfoService.findToxinBynName(tooxins[i1]);
                toxinId.add(toxinBynName);
            }

            String oungNum = (String) li.get(18);
            String[] oungNums = oungNum.split(",");
            String word = (String) li.get(19);
            String[] words = word.split(",");
            String txt = (String) li.get(20);
            String[] txts = txt.split(",");
            String png = (String) li.get(21);
            String[] pngs = png.split(",");
            sampleInfoService.insertInfo(sampleId,isdel,categoryId,cropCpeciesId,sheng,shi,xian,xiang,cun,hu,hTime,sTime,samPeople,seasonal,description,pollutionRate,toxinId,oungNums,words,txts,pngs);
        }
        return "IM";
    }



}
